package com.pw.study.arithmetic.task

import com.pw.study.arithmetic.stack.FutureStackWithOperation

import scala.util.control.Breaks

/**
 * @Desc: 计算表达式
 * @author: future
 * @since: 2022/5/30-21:15
 */
object CalculatorTask {
  def main(args: Array[String]): Unit = {
    val expression = "7*2*2-5+1-5+3-4"
    val stackNum = new FutureStackWithOperation(10)
    val stackOp: FutureStackWithOperation = new FutureStackWithOperation(10)
    var index = 0
    var num1 = 0
    var num2 = 0
    var op = 0
    var res = 0
    var ch: Char = ' '
    var keepNum = ""

    Breaks.breakable {
      while (true) {
        ch = expression.substring(index, index + 1)(0)
        if (stackOp.isOper(ch)) {
          if (!stackOp.isEmpty()) {
            if (stackOp.priority(ch) <= stackOp.priority(stackOp.stack(stackOp.top))) {
              num1 = stackNum.pop().toString.toInt
              num2 = stackNum.pop().toString.toInt
              op = stackOp.pop().toString.toInt
              res = stackNum.cal(num1, num2, op)
              stackNum.push(res)
              stackOp.push(ch)
            } else {
              stackOp.push(ch)
            }
          } else {
            stackOp.push(ch)
          }
        } else {
          keepNum += ch
          if (index == expression.length - 1) {
            stackNum.push(keepNum.toInt)
          } else {
            if (stackOp.isOper(expression.substring(index + 1, index + 2)(0))) {
              stackNum.push(keepNum.toInt)
              keepNum = ""
            }

          }
        }
        index += 1
        if (index >= expression.length) {
          Breaks.break()
        }
      }
    }
    Breaks.breakable {
      while (true) {
        if (stackOp.isEmpty()) {
          Breaks.break()
        }
        num1 = stackNum.pop().toString.toInt
        num2 = stackNum.pop().toString.toInt
        op = stackOp.pop().toString.toInt
        res = stackNum.cal(num1, num2, op)
        stackNum.push(res)
      }
    }
    val res2 = stackNum.pop()
    println(s"表达式$expression = $res2")
  }
}
